<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="always">
      <!-- 添加分类按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="getParentCate">添加分类</el-button>
        </el-col>
      </el-row>
      <el-table
      :data="cateList"
      style="width: 100%"
      border
      row-key="cat_id"
      :tree-props="{children: 'children'}">
      <el-table-column type="index">
        <template v-slot="scope">
          {{indexCount(scope.row)}}
        </template>
      </el-table-column>
      <el-table-column prop="cat_name" label="分类名称"></el-table-column>
      <el-table-column prop="cat_deleted" label="是否有效">
        <template v-slot="scope">
          <i class="el-icon-success" v-if="!scope.row.cat_deleted"></i>
          <i class="el-icon-error" v-else></i>
        </template>
      </el-table-column>
      <el-table-column prop="cat_level" label="排序">
        <template v-slot="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template v-slot="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="editCateById(scope.row.cat_id)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteCate(scope.row.cat_id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 页码条 -->
      <el-pagination
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[5, 8, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addCateDialogClose">
      <el-form ref="dialogForm" :model="addCateForm" :rules="addCateFormRule" :status-icon="true">
        <el-form-item label="分类名称" label-width="90px" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类" label-width="90px">
          <el-cascader
            v-model="selectKeys"
            :options="cateParentList"
            :props="{value: 'cat_id', label: 'cat_name', expandTrigger: 'hover', checkStrictly: true}"
            @change="cateParentChange"
            clearable></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="$refs.dialogForm.resetFields()">
      <el-form ref="dialogForm" :model="editCateForm" :rules="addCateFormRule" :status-icon="true">
        <el-form-item label="分类名称" label-width="90px" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { getHomeData } from 'network/home.js';

  export default {
    name: 'Cate',
    data() {
      return {
        queryInfo: {
          type: 3,
          pagenum: 1,
          pagesize: 5
        },
        cateList: [],
        total: 0,
        addDialogVisible: false,
        addCateForm: {
          // 分类名称
          cat_name: '',
          // 分类id，若为1级，则应当为0
          cat_pid: 0,
          // 分类层级：0为1级
          cat_level: 0
        },
        addCateFormRule: {
          cat_name: [
            { required: true, message: '请添加分类名称', trigger: 'blur' }
          ]
        },
        cateParentList: [],
        // 选中的父级分类
        selectKeys: [],
        editDialogVisible: false,
        editCateForm: {}
      }
    },
    created() {
      this.getCateList();
    },
    methods: {
      // 获取所有商品分类
      getCateList() {
        getHomeData({
          url: 'categories',
          params: this.queryInfo
        })
        .then(res => {
          this.total = res.data.total;
          this.cateList = res.data.result;
        })
      },
      // 更改当前页面展示数据的条数
      handleSizeChange(newSize) {
        this.queryInfo.pagesize = newSize;
        this.getCateList();
      },
      // 更改当前页面的页数
      handleCurrentChange(newNum) {
        this.queryInfo.pagenum = newNum;
        this.getCateList();
      },
      indexCount(cate) {
        if(cate.children && cate.children[0].children) {
          return '#';
        }
        return ;
      },
      // 根据id获取所要编辑的分类的信息
      editCateById(id) {
        getHomeData({
          url: `categories/${id}`
        })
        .then(res => {
          this.editCateForm = res.data;
        })
        .catch(() => this.$message.error(new Error('获取分类失败')))
        this.editDialogVisible = true;
      },
      // 编辑分类
      editCate() {
        this.$refs.dialogForm.validate(valid => {
          if(!valid) return;
          getHomeData({
            url: `categories/${this.editCateForm.cat_id}`,
            data: {
              cat_name: this.editCateForm.cat_name
            }
          }, 'put')
          .then(res => {
            if(res.meta.status !== 200) 
              return this.$message({
                type: 'error',
                message: res.meta.msg
              });
              this.$message({
                type: 'success',
                message: res.meta.msg
              })
              this.getCateList();
              this.editDialogVisible = false;
          })
        })
      },
      // 根据id删除对应分类
      deleteCate(id) {
        this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          return getHomeData({
            url: `categories/${id}`
          }, 'delete')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已经取消删除'
          })
          return new Promise(() => {});
        })
        .then(res => {
            this.$message({
              type: 'success',
              message: res.meta.msg
            })
            this.getCateList()
          })
          .catch(() => {
            this.$message({
              type: 'error',
              message: new Error('删除失败')
            })
            return new Promise(() => {});
          })
      },
      // 获取所有父级分类
      getParentCate() {
        getHomeData({
          url: 'categories',
          params: {
            type: 2
          }
        })
        .then(res => {
          if(res.meta.status !== 200) 
            return this.$message({
              type: 'error',
              message: res.meta.msg
            })
            this.cateParentList = res.data
        })
        this.addDialogVisible = true
      },
      // 添加分类
      addCate() {
        this.$refs.dialogForm.validate(valid => {
          if(!valid) return;
          getHomeData({
            url: 'categories',
            data: this.addCateForm
          }, 'post')
          .then(res => {
            console.log(res);
            if(res.meta.status !== 201) {
              return this.$message({
                type: 'error',
                message: res.meta.msg
              });
            }
            this.$message({
              type: 'success',
              message: res.meta.msg
            });
            this.getCateList();
            this.addDialogVisible = false;
          })
        })
      },
      // 监听级联选择其的更改
      cateParentChange() {
        let length = this.selectKeys.length;
        // 若length > 0则说明其选中了父级分类，否则就没有选中
        if(length > 0) {
          this.addCateForm.cat_pid = this.selectKeys[length - 1];
          this.addCateForm.cat_level = length;
        }else {
          this.addCateForm.cat_pid = 0;
          this.addCateForm.cat_level = 0;
        }
      },
      // 清空表单和级联选择器内容
      addCateDialogClose() {
        this.$refs.dialogForm.resetFields();
        this.selectKeys = [];
        this.addCateForm.cat_pid = 0;
        this.addCateForm.cat_level = 0;
      },

    },
    computed: {
      
    },
  }
</script>

<style scoped>
  .el-row {
    margin-bottom: 15px;
  }
  .el-icon-success {
    color: rgb(17, 219, 17);
    font-size: 18px;
  }
  .el-icon-error {
    color: rgb(235, 63, 63);
    font-size: 18px;
  }
  .el-pagination { 
    margin-top: 10px;
  }
</style>